var express = require("express");
var router = express.Router();


var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var multer = require("multer");
var shortid = require("shortid");


var user = require("../model/user");
var essay = require("../model/essay");



var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, "./static/uploads/");
    },
    filename: function(req, file, cb) {

        fileName = shortid.generate() + file.originalname;
        cb(null, fileName);
    }
});

var upload = multer({ storage: storage });

router.post("/upload-image", upload.single("upload_file"), function(req, res) {
    res.send({
        code: 0,
        status: 0,
        message: "上传成功",
        file_path: "/uploads/" + req.file.filename
    });
});

router.get("/editor", function(req, res) {
    var userId = req.session.passport.user;
    essay.find({ user: userId }, function(err, docs) {
        res.render("editor", { layout: "editor", essays: docs });
    });
});

router.get("/editor/:essayId", function(req, res) {
    var userId = req.session.passport.user;
    var essayId = req.params.essayId;

    essay.find({ user: userId }, function(err, docs) {
        essay.findById(essayId).exec(function(err, doc) {
            console.log(doc);
            res.render("editor", { layout: "editor", essays: docs, essay: doc });
        });
    });
});

router.post("/add-essay", function(req, res) {
    var title = "无标题文章";
    var content = "";
    var userId = req.session.passport.user;

    essay.create({
            title: title,
            content: content,
            user: userId
        },
        function(err, doc) {
            console.log(doc);
            res.send({ code: 0, status: 0, message: "添加成功", essayId: doc._id });
        }
    );
});

router.post("/update-essay", urlencodedParser, function(req, res) {
    var essayId = req.body.essayId;
    var title = req.body.title;
    var content = req.body.content;
    var abstract = req.body.abstract;
    var userId = req.session.passport.user;

    essay.update({ _id: essayId }, {
            title: title,
            content: content,
            abstract: abstract,
            updateTime: Date.now()
        },
        function(err, doc) {
            res.send({ code: 0, status: 0, message: "修改成功" });
        }
    );
});

router.post("/delete-essay", urlencodedParser, function(req, res) {
    var essayId = req.body.essayId;

    essay.remove({ _id: essayId }, function(err, doc) {
        res.send({ code: 0, status: 0, message: "删除成功" });
    });
});


module.exports = router;